package icu.bughub.app.app.ui.components.video

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.view.View
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.filled.FullscreenExit
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.PlayCircle
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import coil.compose.AsyncImage
import java.util.Timer
import java.util.TimerTask

@SuppressLint("DefaultLocale")
@Composable
fun VideoPlayer(vodController: VodController) {

    var timeFormatText by remember {
        mutableStateOf("")
    }

    val MILLS_PER_SECOMND = 1000
    val MILLS_PER_MINUTE = 60000
    val SECONDS_PER_MINUTE = 60

    LaunchedEffect(vodController.playerValue.currentPosition) {
        val position = vodController.playerValue.currentPosition
        val duration = vodController.playerValue.duration

        // 格式化时间
        timeFormatText =
            String.format(
                "%02d:%02d:%02d / %02d:%02d:%02d",
                position / MILLS_PER_MINUTE / SECONDS_PER_MINUTE,
                position / MILLS_PER_MINUTE,
                position / MILLS_PER_SECOMND % SECONDS_PER_MINUTE,
                duration / MILLS_PER_MINUTE / SECONDS_PER_MINUTE,
                duration / MILLS_PER_MINUTE,
                duration / MILLS_PER_SECOMND % SECONDS_PER_MINUTE,
            )
    }


    //是否显示控制层
    var isShowControlBar by remember {
        mutableStateOf(false)
    }

    var timer: Timer? = null

    val configuration = LocalConfiguration.current

    val context = LocalContext.current

    val lifecycleOwner = LocalLifecycleOwner.current

    //监听生命周期
    DisposableEffect(vodController) {
        val lifecycleEventObserver = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_RESUME -> {
                    vodController.resume()
                }

                Lifecycle.Event.ON_PAUSE -> {
                    vodController.pause()
                }

                else -> {

                }
            }
        }
        lifecycleOwner.lifecycle.addObserver(lifecycleEventObserver)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(lifecycleEventObserver)
            vodController.pause()
        }

    }

    //处于横屏状态时需要监听物理返回键，回到竖屏状态  监听手机返回键  横屏状态启用
    BackHandler(enabled = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            context.findActivity()?.requestedOrientation =
                ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
    }
    // 实现视频播放逻辑
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .clickable(
                //去除点击效果 水波纹效果
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = {
                    timer?.cancel()
                    timer = null
                    if (!isShowControlBar) {
                        timer = Timer()
                        timer?.schedule(object : TimerTask() {
                            override fun run() {
                                isShowControlBar = false
                            }
                        }, 3000)
                    }
                    isShowControlBar = !isShowControlBar
                })
    ) {
        // 视频播放器区域
        VideoView(vodPlayer = vodController.vodPlayer)
        //正在加载层
        if (vodController.playerValue.state == PlayState.LOADING) {
            CircularProgressIndicator(
                modifier = Modifier
                    .align(Alignment.Center)
                    .size(40.dp)
            )
        }

        //视频封面
        if (vodController.playerValue.state == PlayState.NONE
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Blue)
                    .height(300.dp),
                contentAlignment = Alignment.Center
            ) {
                AsyncImage(
                    model = vodController.playerValue.coverUrl, contentDescription = "视频封面",
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .fillMaxSize()
                        //.aspectRatio(16 / 9f)
                        .height(300.dp)
                        .align(Alignment.Center)
                )

                IconButton(
                    onClick = {
                        vodController.startVodPlay()
                    },
                    modifier = Modifier
                        .align(Alignment.Center)
                        .padding(top = 50.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.PlayCircle, contentDescription = "播放",
                        tint = Color.White,
                        modifier = Modifier
                            .size(50.dp)
                    )
                }
            }
        }

        if (isShowControlBar) {
            //视频控制层
            Column(
                modifier = Modifier
                    .fillMaxSize(),
                verticalArrangement = Arrangement.SpaceBetween
            ) {

                if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                    Spacer(modifier = Modifier.weight(1f))
                } else {
                    Row(
                        verticalAlignment = Alignment.Top,
                        modifier = Modifier
                            .height(45.dp)
                            .weight(1f)
                            .fillMaxWidth()
                            .background(
                                Brush.verticalGradient(
                                    listOf(
                                        Color.Black,
                                        Color.Transparent
                                    )
                                )
                            )
                    ) {
                        IconButton(onClick = {
                            context.findActivity()?.requestedOrientation =
                                ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
                        }) {
                            Icon(
                                imageVector = Icons.Default.ArrowBack, contentDescription = "返回",
                                tint = Color.Red,
                                modifier = Modifier
                                    .padding(8.dp)
                            )
                        }
                        Text(
                            text = vodController.playerValue.title,
                            color = Color.Red,
                            fontSize = 18.sp
                        )
                    }
                }
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(45.dp)
                        .background(
                            Brush.verticalGradient(listOf(Color.Transparent, Color.Black))
                        ),
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    //播放或者暂停按钮
                    IconButton(onClick = {
                        if (vodController.playerValue.state == PlayState.PLAYING) {
                            //暂停
                            vodController.pause()
                        } else {
                            //播放
                            vodController.resume()
                        }
                    }) {
                        if (vodController.playerValue.state == PlayState.PLAYING) {
                            //暂停
                            Icon(
                                imageVector = Icons.Default.Pause,
                                contentDescription = "暂停",
                                tint = Color.White
                            )
                        } else {
                            //播放
                            Icon(
                                imageVector = Icons.Default.PlayArrow,
                                contentDescription = "播放",
                                tint = Color.White
                            )
                        }

                    }

                    Spacer(modifier = Modifier.width(8.dp))
                    //视频进度条
                    Slider(
                        colors = androidx.compose.material3.SliderDefaults.colors(
                            thumbColor = Color.Transparent,
                            activeTrackColor = Color.White,
                            inactiveTrackColor = Color.Transparent.copy(alpha = 0.3f),
                        ),
                        value = vodController.playerValue.currentPosition.toFloat(),
                        onValueChange = {
                            // 实现视频进度条拖动逻辑
                            vodController.playerValue.currentPosition = it.toLong()
                            vodController.seekTo(it.toLong())
                        }, valueRange = 0f..vodController.playerValue.duration.toFloat(),
                        modifier = Modifier
                            .weight(1f)
                            .height(2.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))

                    Text(text = timeFormatText, color = Color.White, fontSize = 14.sp)

                    Spacer(modifier = Modifier.width(8.dp))

                    //控制全屏按钮
                    IconButton(onClick = {
                        if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                            context.findActivity()?.requestedOrientation =
                                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                            context?.findActivity()?.window?.decorView?.systemUiVisibility =
                                (View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE)
                        } else {
                            context.findActivity()?.requestedOrientation =
                                ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
                        }
                    }) {
                        if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                            Icon(
                                imageVector = Icons.Default.Fullscreen,
                                contentDescription = "全屏",
                                tint = Color.White
                            )
                        } else {
                            Icon(
                                imageVector = Icons.Default.FullscreenExit,
                                contentDescription = "关闭全屏",
                                tint = Color.White
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.width(8.dp))

            }
        }
    }
}

//查找Activity
fun Context.findActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.findActivity()
    else -> null
}